package com.itheima.reggie.interceptor;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.Employee;
import com.itheima.reggie.entity.User;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@Configuration
public class UserInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //获取当前session 登录对象
        Object userLogin = request.getSession().getAttribute("userLogin");
//        System.out.println(request.getRequestURL()+"====================================>"+BaseContext.getThreadLocal());
        if( userLogin == null){
            //未登录 跳转到登录页面
            System.out.println("未登录 跳转");
            response.setContentType("application/json;charset=utf-8");
            String jsonString=JSON.toJSONString(R.error("未登录"));
            response.getWriter().write(jsonString);
            return false;
        }
        if("异地登录".equals(userLogin.toString())){
            System.out.println("准备退出user账户");
            response.setContentType("application/json;charset=utf-8");
            String jsonString=JSON.toJSONString(R.error("异地登录"));
            response.getWriter().write(jsonString);
            request.getSession().removeAttribute("userLogin");
            return false;
        }
            User user =(User) userLogin;
            BaseContext.setThreadLocal(user.getId());
//            System.out.println("登录成功已存入用户ID======================>"+BaseContext.getThreadLocal());
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        HandlerInterceptor.super.afterCompletion(request, response, handler, ex);
    }
}
